package com.imooc.controller;

import com.imooc.utils.IMOOCJSONResult;
import com.imooc.utils.ValBean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName: ValidateController
 * @Package: com.imooc.controller
 * @Description:
 * @Date: 2021/7/22 15:13
 * @Author: sunzheng@beiming.com
 */
@Controller
@RequestMapping(value = "/val")
public class ValidateController {

  @RequestMapping(value = "/val", method = RequestMethod.POST)
  @ResponseBody
  public IMOOCJSONResult val(@Valid @RequestBody ValBean bean, BindingResult result)
      throws Exception {

    if (result.hasErrors()) {
      //如果没有通过,跳转提示
      Map<String, String> map = getErrors(result);
      return IMOOCJSONResult.errorMap(map);
    } else {
      //继续业务逻辑
    }

    return IMOOCJSONResult.ok();
  }

  private Map<String, String> getErrors(BindingResult result) {
    Map<String, String> map = new HashMap<String, String>();
    List<FieldError> list = result.getFieldErrors();
    for (FieldError error : list) {
      System.out.println("error.getField():" + error.getField());
      System.out.println("error.getDefaultMessage():" + error.getDefaultMessage());

      map.put(error.getField(), error.getDefaultMessage());
    }
    return map;
  }
}
